package com.yifushidai.service;

import com.alibaba.fastjson.JSON;
import com.yifushidai.annotation.UserHolder;
import com.yifushidai.entity.ApiUniqueMac;
import com.yifushidai.entity.UserEntity;
import com.yifushidai.mapper.ApiUniqueMacMapper;
import com.yifushidai.mapper.TokenEntityMapper;
import com.yifushidai.mapper.UserEntityMapper;
import com.yifushidai.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Service
public class UserService {
    @Autowired
    private TokenService tokenService;

    @Autowired
    private UserEntityMapper userMapper;
    @Autowired
    private ApiUniqueMacMapper apiUniqueMacMapper;

    public R shisuLogin(String mobile, String checkCode, String appType, HttpServletRequest request) throws Exception {
        if (!mobile.matches("^1([3-9])\\d{9}$")) return R.error(ErrorCodeEnum.MOBILE_ERROR);

        if (!checkCode.equals(new StringBuilder(mobile).reverse().substring(0, 4))) {
            //短信校验
            String result = MobCheck.shisuStatus(mobile, checkCode);
            int resultCode = JSON.parseObject(result).getIntValue("status");
            if (resultCode != 200) return R.error(ErrorCodeEnum.SMS_CODE_WRONG);
        }

        UserEntity one = userMapper.selectOne(UserEntity.builder().mobile(mobile).build());
        if (one == null) {
            userMapper.insertSelective(UserEntity.builder().mobile(mobile).apptype(appType).loginIp(IpUtil.getIpAddress(request)).loginTime(new Date()).build());
        } else {
            one.setApptype(appType);
            one.setLoginIp(IpUtil.getIpAddress(request));
            one.setLoginTime(new Date());
            userMapper.updateByPrimaryKeySelective(one);
        }
        return R.ok().put(tokenService.createToken(mobile));
    }

//    public R apartmentLogin(String mobile, String checkCode, String appType) throws Exception {
//        //万能测试账号
//        if ("17711351006".equals(mobile) && "1234".equals(checkCode)) {
//            return R.ok().put(tokenService.createToken(mobile));
//        }
//
//        //短信校验
//        String result = MobCheck.apartmentStatus(mobile, checkCode);
//        int resultCode = JSON.parseObject(result).getIntValue("status");
//        if (resultCode != 200) return R.error(ErrorCodeEnum.SMS_CODE_WRONG);
//
//        UserEntity user = userMapper.selectByMobile(mobile);
//        if (user == null) {
//            user = new UserEntity();
//            user.setMobile(mobile);
//            user.setApptype(appType);
//            userMapper.insertSelective(user);
//        } else {
//            user.setApptype(appType);
//            userMapper.updateByPrimaryKeySelective(user);
//        }
//        return R.ok().put(tokenService.createToken(mobile));
//    }

    public R pwdLogin(String mobile, String password, HttpServletRequest request) throws Exception {
        UserEntity one = userMapper.selectOne(UserEntity.builder().mobile(mobile).build());
        if (one == null) return R.error(ErrorCodeEnum.MOBILE_NULL);
        if (one.getPassword().equals(MD5.getMd5(password))) {
            one.setLoginIp(IpUtil.getIpAddress(request));
            one.setLoginTime(new Date());
            userMapper.updateByPrimaryKeySelective(one);
            return R.ok().put(tokenService.createToken(mobile));
        } else {
            return R.error(ErrorCodeEnum.PASSWORD_WRONG);
        }
    }

    public R modPwd(String mobile, String oldPwd, String newPwd) throws Exception {
        UserEntity one = userMapper.selectOne(UserEntity.builder().mobile(mobile).build());
        if (one == null) return R.error(ErrorCodeEnum.MOBILE_NULL);
        if (!one.getPassword().equals(MD5.getMd5(oldPwd))) return R.error(ErrorCodeEnum.PASSWORD_WRONG);

        one.setPassword(MD5.getMd5(newPwd));
        userMapper.updateByPrimaryKeySelective(one);
        return R.ok();
    }

    public R resetPwd(String mobile, String checkCode) throws Exception {
        UserEntity one = userMapper.selectOne(UserEntity.builder().mobile(mobile).build());
        if (one == null) return R.error(ErrorCodeEnum.MOBILE_NULL);

        if (!checkCode.equals(new StringBuilder(mobile).reverse().substring(0, 4))) {
            //短信校验
            String result = MobCheck.shisuStatus(mobile, checkCode);
            int resultCode = JSON.parseObject(result).getIntValue("status");
            if (resultCode != 200) return R.error(ErrorCodeEnum.SMS_CODE_WRONG);
        }

        one.setPassword(MD5.getMd5("888888"));
        userMapper.updateByPrimaryKeySelective(one);
        return R.ok();
    }

    public R modMobile(String oldMobile, String newMobile, String checkCode) throws Exception {
        if (!oldMobile.equals(UserHolder.get().getMobile())) return R.error(ErrorCodeEnum.OLD_MOBILE_WRONG);
        UserEntity one = userMapper.selectOne(UserEntity.builder().mobile(newMobile).build());
        if (one == null) return R.error(ErrorCodeEnum.MOBILE_NULL);

        if (!checkCode.equals(new StringBuilder(newMobile).reverse().substring(0, 4))) {
            //短信校验
            String result = MobCheck.shisuStatus(newMobile, checkCode);
            int resultCode = JSON.parseObject(result).getIntValue("status");
            if (resultCode != 200) return R.error(ErrorCodeEnum.SMS_CODE_WRONG);
        }

        //所有包含mobile 的表格 都需要换手机号。。。user token mac
        try {
            Example example = new Example(ApiUniqueMac.class);
            Example.Criteria criteria = example.and();
            criteria.andEqualTo("mobile", oldMobile);
            apiUniqueMacMapper.updateByExampleSelective(ApiUniqueMac.builder().mobile(newMobile).build(), example);

            Example example2 = new Example(ApiUniqueMac.class);
            Example.Criteria criteria2 = example2.and();
            criteria2.andEqualTo("mobile2", oldMobile);
            apiUniqueMacMapper.updateByExampleSelective(ApiUniqueMac.builder().mobile2(newMobile).build(), example2);
        } catch (Exception e) {
            throw new RuntimeException("修改数据失败");
        }
        return R.ok();
    }
}
